#include "bt.h"

BluetoothSerial SerialBT;

const int ledPin = 2;
bool ledState = LOW;
bool isConnected = false;

// 初始化蓝牙
void InitBT() {
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, ledState);

    Serial.begin(115200);
    SerialBT.begin("kaedeBT");  // 设备名
    Serial.println("Bluetooth device started, waiting for connection...");

    // 注册蓝牙事件回调
    SerialBT.register_callback(btCallback);
}

bool isBTConnected() {
    return isConnected;
}

BluetoothSerial& GetBT() {
    return SerialBT;
}

void handleBTData(const char* data, size_t len);

// 处理蓝牙事件
void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
    switch (event) {
        case ESP_SPP_SRV_OPEN_EVT:  // 客户端连接
            isConnected = true;
            Serial.println("Device connected");
            SerialBT.println("Welcome! Bluetooth connected.");
            break;

        case ESP_SPP_CLOSE_EVT:  // 客户端断开
            isConnected = false;
            Serial.println("Device disconnected");
            break;

        case ESP_SPP_DATA_IND_EVT:  // 收到数据
            handleBTData((const char*)param->data_ind.data, param->data_ind.len);
            break;

        default:
            break;
    }
}

